#coding=utf-8

import sys #要重新载入sys。因为 Python 初始化后会删除 sys.setdefaultencoding 这个方 法
reload(sys)
sys.setdefaultencoding('utf-8')
from common import md5
from XMLGenerator.XMLFileGenerator import XMLFileGenerator

OPERATION_TYPE_APPENDIX = 0
OPERATION_TYPE_FIRST_LEVEL = 1
OPERATION_TYPE_SECOND_LEVEL = 2
OPERATION_TYPE_THIRD_LEVEL = 3

OPERATION_ADD = 1
OPERATION_REPLACE = 2
OPERATION_DELETE = 3

HT_TYPE_CONTRACT = 'contract'
HT_TYPE_EMPLOYEE = 'employee'
HT_TYPE_COMPETITION = 'competition'
HT_TYPE_SECRET = 'secret'


def _error(msg):
    sys.stderr.write('%s\n'%msg)
    raise Exception(msg)

class HTBaseGenerator(object):
    def __init__(self, special_rows, industry_name,generate_file_type ,ht_set_type, original_contract_file, saved_dir):
        self.generate_file_type = generate_file_type
        self.special_rows = special_rows
        self.industry_name = industry_name
        self.ht_set_type = ht_set_type
        self.original_contract_file = original_contract_file
        self.saved_dir = saved_dir
        self.current_row_index = 0

        self.jobid2_industy_job = {}
        self.jobid2htfile = {}
        self.htid2htfile = {}
        self.repeat_jobs = []
        #带替换的条款组
        self.waiting_replace_rows = []
        self.init_data()
    #子类重写此方法
    def init_data(self):
        pass

    #处理附件
    def deal_appendix_row(self, special_row, xml_generator):
        pass

    #根据条款 获得 需要条款的属性
    def get_attrib(self, special_row):
        return {}

    def generate_contract(self):
        #提取行业职位
        pre_job_identity = None
        current_xml_generator = None
        contract_number = 1
        job_number = 0
        for index, special_row in enumerate(self.special_rows):
            self.current_row_index = index
            job_identity = "%s_%s" %(self.industry_name, special_row.job)
            #初始化新一份劳动合同
            if pre_job_identity == None or pre_job_identity != job_identity:
                job_number += 1
                print "INFO--------%d %s ----------" % (job_number, job_identity)
                contract_number = self._save_xml(pre_job_identity, current_xml_generator, contract_number)
                current_xml_generator = XMLFileGenerator(self.original_contract_file)

            pre_job_identity = job_identity
            self._deal_per_special_row(special_row, current_xml_generator)
        #保存最后一份合同
        contract_number = self._save_xml(pre_job_identity, current_xml_generator, contract_number)

        if len(self.repeat_jobs) > 0:
            print "WARNING: %s 存在重复职位" % "|".join(self.repeat_jobs)


    '''
    将该行业 职位-合同对应表写入文件
    '''
    def write_to_map_file(self, file_name):
        map_file = '%s/%s' % (self.saved_dir, file_name)

        fo = open(map_file, mode='wb')

        for job_id, htfile in self.jobid2htfile.items():
            writing_items = []

            job_identity = self.jobid2_industy_job[job_id]
            industry_job = job_identity.split('_')
            industry = None
            job = None
            if len(industry_job) == 2:
                industry = industry_job[0]
                job = industry_job[1]
            if industry is None or job is None:
                _error("Error:%s 写入到 %s 时出错" % job_identity, map_file)
                continue

            writing_items.append(industry)
            writing_items.append(job)
            writing_items.append(self.ht_set_type)
            writing_items.append(htfile)

            writing_items.append("\n")
            fo.write(" ".join(writing_items))
        fo.close()

    def _deal_per_special_row(self, special_row, xml_generator):

        #处理附件
        operation_types = [OPERATION_TYPE_FIRST_LEVEL, OPERATION_TYPE_SECOND_LEVEL, OPERATION_TYPE_THIRD_LEVEL]
        if special_row.operation_object_type == OPERATION_TYPE_APPENDIX:
            self.deal_appendix_row(special_row, xml_generator)

        elif special_row.operation_object_type in operation_types:

            if special_row.operation_type == OPERATION_REPLACE:
                if special_row.operation_object_type == OPERATION_TYPE_FIRST_LEVEL:

                    self.waiting_replace_rows.append(special_row)

                    self._check_replace_elements(xml_generator, special_row)

                else:
                    new_attri = self.get_attrib(special_row)
                    xml_generator.replace_element({'law_id':special_row.clause_location}, new_attri ,special_row.content)


            else:

                if special_row.operation_type == OPERATION_DELETE:
                    xml_generator.delete_element({'law_id':special_row.clause_location})
                    pass
                elif special_row.operation_type == OPERATION_ADD:
                    new_attri = {}
                    xml_generator.add_element({'law_id':special_row.clause_location}, new_attri, special_row.content)
                    pass

    #判断该行是不是替换条款的的最后一行
    def _check_replace_elements(self, xml_generator, current_row):

        if xml_generator is None:
            return

        isNeedReplace = True
        #该行为所有行的最后一行
        if self.current_row_index <  len(self.special_rows)-1:
            next_row = self.special_rows[self.current_row_index+1]
            #必须是同一个职位

            if next_row.job == current_row.job and next_row.operation_type == OPERATION_REPLACE and next_row.operation_object_type == OPERATION_TYPE_FIRST_LEVEL and next_row.clause_location == current_row.clause_location:
                isNeedReplace = False


        if isNeedReplace and len(self.waiting_replace_rows) > 0:
            first_row = self.waiting_replace_rows[0]
            new_attri = self.get_attrib(first_row)
            xml_generator.replace_elements({'law_id':first_row.clause_location},new_attri, self._get_waiting_replace_clauses())
            self.waiting_replace_rows = []

    '''
    将xml写入文件
    '''
    def _save_xml(self, saved_job_identity, current_xml_generator, contract_number, file_name=None):
        if current_xml_generator is not None:
            if file_name is None:
                file_name = "%s%d.xml" % (self.generate_file_type,contract_number)
            file_path = "%s/%s" % (self.saved_dir,file_name)
            xml_md5 = current_xml_generator.xml_md5()
            #如果是一份新的合同，保存
            if xml_md5 not in self.htid2htfile:
                current_xml_generator.save(file_path)
                contract_number += 1
                self.htid2htfile[xml_md5] = file_name
            else:
                file_name = self.htid2htfile[xml_md5]

            pre_job_id = md5(saved_job_identity)
            if pre_job_id in self.jobid2htfile:
                self.repeat_jobs.append(saved_job_identity)

            self.jobid2htfile[pre_job_id] = file_name

        return contract_number

    #从待替换行里面提取所有的条款
    def _get_waiting_replace_clauses(self):
        clauses = []
        for row in self.waiting_replace_rows:
            clauses.append(row.content)

        return clauses
